package com.umeox.watch.moto.dataservice.stub;

import android.os.Binder;

import com.umeox.moto.common.log.Logger;
import com.umeox.watch.location.proto.LocationProto;
import com.umeox.watch.moto.dataservice.BuildConfig;
import com.umeox.watch.moto.dataservice.DataProvider;
import com.umeox.watch.moto.dataservice.base.BaseApp;
import com.umeox.watch.moto.dataservice.interfaces.ILocation;
import com.umeox.watch.moto.dataservice.services.LocationService;
import com.umeox.watch.moto.dataservice.utils.LocationHelper;

import net.vidageek.mirror.dsl.Mirror;

import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class LocationStub extends Binder implements ILocation {
    private final String TAG = "Location.Stub";

    public LocationStub() {
        this.attachInterface(this, DESCRIPTOR);
    }

    public static void registerBinder() {
        try {
            new Mirror().on("android.os.ServiceManager").invoke().method("addService").withArgs(BuildConfig.sosBinderName, new LocationStub());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public android.os.IBinder asBinder() {
        return this;
    }

    @Override
    public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException {
        switch (code) {
            case INTERFACE_TRANSACTION: {
                reply.writeString(DESCRIPTOR);
                return true;
            }
            case TRANSACTION_REQUESTLOCATION: {
                data.enforceInterface(DESCRIPTOR);
                String reqUser = data.readString();
                String locCode = data.readString();
                String priority = data.readString();
                this.requestLocation(reqUser, locCode, priority);
                reply.writeNoException();
                return true;
            }
            case TRANSACTION_REQUESTLOCATION4SOS: {
                data.enforceInterface(DESCRIPTOR);
                byte[] result = this.requestLocation4Sos();
                reply.writeNoException();
                reply.writeByteArray(result);
                return true;
            }
            default: {
                return super.onTransact(code, data, reply, flags);
            }
        }
    }

    @Override
    public void requestLocation(String reqUser, String locCode, String priority) {
        String reportReasonAttr = reqUser + "#" + locCode;
        Logger.d("远程定位请求>>>" + reportReasonAttr);
        LocationService.cmdReqLocation(BaseApp.getInstance(), reportReasonAttr, Integer.parseInt(priority));
    }

    @Override
    public byte[] requestLocation4Sos() {
        final Thread[] thread = {Thread.currentThread()};
        Logger.w(TAG + ">>>收到SOS定位请求(" + thread[0].getId() + ")");
        LocationProto.LocationDetail.Builder locBuilder = LocationProto.LocationDetail.newBuilder()
                .setStartTime(System.currentTimeMillis())
                .setLocReason(LocationProto.LocReason.forNumber(LocationProto.LocReason.SOS_LOCATION_VALUE))
                .setLocReasonAttr("")
                .setHolderId(DataProvider.getHolderId())
                .setEventId(UUID.randomUUID().toString())
                .setLocPriority(LocationProto.LocPriority.PRIORITY_NETWORK_VALUE);

        CountDownLatch downLatch = new CountDownLatch(1);
        LocationHelper currentRequest = LocationHelper.getHelper(BaseApp.getInstance());
        currentRequest.setLocListener(new LocationHelper.LocationCompleteListener() {
            @Override
            public void onStateChange(String message) {
                Logger.i(TAG + ">>>SOS定位（" + thread[0].getId() + "）-> " + message);
            }

            @Override
            public void onFirstLocationSuccess(LocationProto.LocationDetail.Builder locBuilder) {

            }

            @Override
            public void onLocationSuccess(final LocationProto.LocationDetail.Builder result) {
                Logger.w(TAG + ">>>onLocationSuccess SOS定位（" + thread[0].getId() + "）完成");
                downLatch.countDown();
            }

            @Override
            public void onLocationFailed(LocationProto.LocationDetail.Builder result) {
                Logger.w(TAG + ">>>onLocationFailed SOS定位（" + thread[0].getId() + "）完成");
                downLatch.countDown();
            }
        });
        currentRequest.requestLocation(locBuilder);
        if (currentRequest.isWorking()
                && downLatch.getCount() > 0) {
            try {
                Logger.w(TAG + ">>>等待定位（" + thread[0].getId() + "）结果");
                downLatch.await(15, TimeUnit.SECONDS);
            } catch (Exception ignored) {
            }
        }
        LocationProto.LocationDetail locationInfo = locBuilder.build();
        Logger.w(TAG + ">>>定位完成（" + thread[0].getId() + "）->" + locationInfo);
        return locationInfo.toByteArray();
    }

}
